package com.lambkit.module.cms.web.directive;

import com.jfinal.kit.StrKit;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.db.sql.column.Columns;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("articles")
public class ArticlesDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        String flag = getPara("flag", scope);
        String style = getPara("style", scope);
        Boolean hasThumbnail = getParaToBool("hasThumbnail", scope);
        String orderBy = getPara("orderBy", scope, "id desc");
        int count = getParaToInt("count", scope, 10);


        Columns columns = Columns.create("flag", flag);

        if (StrKit.notBlank(style)) {
            if (style.contains(",")) {
                List<String> styleParas = Arrays.stream(style.split(","))
                        .filter(StrKit::notBlank).map(s -> s.trim()).collect(Collectors.toList());
                columns.in("style", styleParas.toArray());
            } else {
                columns.eq("style", style);
            }
        }

        columns.add("status", CmsArticle.STATUS_NORMAL);

        if (hasThumbnail != null) {
            if (hasThumbnail) {
                columns.notNull("thumbnail");
            } else {
                columns.isnull("thumbnail");
            }
        }

        List<CmsArticle> articles = CmsArticle.service().findListByColumns(columns, orderBy, count);

        if (articles == null || articles.isEmpty()) {
            return;
        }

        scope.setLocal("articles", articles);
        renderBody(env, scope, writer);
    }


    @Override
    public boolean hasEnd() {
        return true;
    }
}
